package com.kcht.rfid.rd30.secretary.dispatch.impl;

import com.kcht.rfid.rd30.secretary.dispatch.IReaderChannel;
import lombok.extern.slf4j.Slf4j;
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;

/**
 * ZmqSocket的代理类，用于控制其线程安全
 * */
@Slf4j
public class ZmqSocketProxy implements IReaderChannel {
    private String ip;
    private Integer port;
    private ZContext context;
    private ZMQ.Socket zmqSocket;

    public ZmqSocketProxy(String ip, int port) {
        this.ip=ip;
        this.port=port;
        resetChannel();
    }

    /**
     * 保证发送和接收同次进行
     * */
    @Override
    public synchronized byte[] sendRecv(byte[] data) {
        zmqSocket.send(data);
        byte[] recv = zmqSocket.recv();
        if(recv==null){
            resetChannel();
        }
        return recv;
    }

    @Override
    public synchronized void close() {
        if(zmqSocket!=null){
            zmqSocket.close();
            context.close();
        }
    }

    @Override
    public String getIp() {
        return ip;
    }

    private synchronized void resetChannel(){
        close();
        this.context = new ZContext();
        this.zmqSocket = context.createSocket(SocketType.REQ);
        this.zmqSocket.setLinger(0);
        this.zmqSocket.setHeartbeatTimeout(2000);
        this.zmqSocket.setReceiveTimeOut(2000);
        this.zmqSocket.setSendTimeOut(2000);
        this.zmqSocket.connect("tcp://" + ip + ":" + port);
    }
}
